package com.hlyue.ingress.consecutiveportalhacking;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;

/**
 * Created by Richard on 2015/8/27.
 */
public class AccessibilityService extends android.accessibilityservice.AccessibilityService {

    private final String TAG = getClass().getName();
    public final static String PACKAGE_INGRESS = "com.nianticproject.ingress";
    private final Handler mHandler = new Handler();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
        NotificationUtils.registerReceivers(this);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        NotificationUtils.unRegisterReceivers(this);
        super.onDestroy();
    }

    @Override
    public void onServiceConnected() {
        //not sure why xml configuration not working.
        AccessibilityServiceInfo accessibilityServiceInfo = getServiceInfo();
        if (accessibilityServiceInfo == null)
            accessibilityServiceInfo = new AccessibilityServiceInfo();
        accessibilityServiceInfo.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
        accessibilityServiceInfo.flags |= AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS;
        accessibilityServiceInfo.packageNames = new String[] {PACKAGE_INGRESS};
        accessibilityServiceInfo.feedbackType = AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
        accessibilityServiceInfo.notificationTimeout = 10;
        setServiceInfo(accessibilityServiceInfo);
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        Log.d(TAG, event.toString());
        final Intent intent = new Intent(this, OverlayViewService.class);
        startService(intent);
        mHandler.removeCallbacksAndMessages(null);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String lastPackage = UsageStateUtils.getLastPackage(AccessibilityService.this);
                if (lastPackage != null && !lastPackage.equals(PACKAGE_INGRESS)) {
                    stopService(intent);
                } else {
                    mHandler.postDelayed(this, 3000);
                }
            }
        }, 3000);
    }

    @Override
    public void onInterrupt() {

    }
}
